package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.slope.data.crack.domain.SlopeCrackData;
import com.ruoyi.slope.data.crack.service.ISlopeCrackDataService;
import com.ruoyi.slope.data.fencenet.domain.SlopeFencenetData;
import com.ruoyi.slope.data.fencenet.service.ISlopeFencenetDataService;
import com.ruoyi.slope.data.geoacoustic.domain.SlopeGeoacousticData;
import com.ruoyi.slope.data.geoacoustic.service.ISlopeGeoacousticDataService;
import com.ruoyi.slope.data.soil.domain.SlopeSoilData;
import com.ruoyi.slope.data.soil.service.ISlopeSoilDataService;
import com.ruoyi.slope.data.weather.domain.SlopeWeatherData;
import com.ruoyi.slope.data.weather.service.ISlopeWeatherDataService;
import com.ruoyi.slope.device.deviceInfo.domain.SlopeDeviceInfo;
import com.ruoyi.slope.device.deviceInfo.service.ISlopeDeviceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 2025/9/4 下午1:36
 */
@Component("RefreshDeviceStatusTask")
public class RefreshDeviceStatusTask {

    @Autowired
    ISlopeDeviceInfoService slopeDeviceInfoService;
    @Autowired
    ISlopeCrackDataService slopeCrackDataService;
    @Autowired
    ISlopeFencenetDataService slopeFencenetDataService;
    @Autowired
    ISlopeGeoacousticDataService slopeGeoacousticDataService;
    @Autowired
    ISlopeSoilDataService slopeSoilDataService;
    @Autowired
    ISlopeWeatherDataService slopeWeatherDataService;

    public void refreshDeviceStatusTask() {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(1L);   // 系统管理员ID
        sysUser.setUserName("admin");

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);

        // 手动放入上下文
        SecurityUtils.setLoginUser(loginUser);


        List<SlopeDeviceInfo> infos = slopeDeviceInfoService.selectSlopeDeviceInfoList(new SlopeDeviceInfo());
        for (SlopeDeviceInfo info : infos) {

            boolean valid = false; // 默认状态为离线/异常

            // 裂缝
            SlopeCrackData crackData = slopeCrackDataService.getLatestCrackData(info.getDeviceSn());
            if (checkValid(crackData == null ? null : crackData.getUpdateTime())) valid = true;

            // 裂缝倾斜
            SlopeCrackData tiltData = slopeCrackDataService.getLatestTiltData(info.getDeviceSn());
            if (checkValid(tiltData == null ? null : tiltData.getUpdateTime())) valid = true;

            // 裂缝加速度
            SlopeCrackData accData = slopeCrackDataService.getLatestAcceleration(info.getDeviceSn());
            if (checkValid(accData == null ? null : accData.getUpdateTime())) valid = true;

            // 围栏加速度
            SlopeFencenetData fencenetAcc = slopeFencenetDataService.getLatestFencenetAcceleration(info.getDeviceSn());
            if (checkValid(fencenetAcc == null ? null : fencenetAcc.getUpdateTime())) valid = true;

            // 围栏倾斜
            SlopeFencenetData fencenetTilt = slopeFencenetDataService.getLatestFencenetTilt(info.getDeviceSn());
            if (checkValid(fencenetTilt == null ? null : fencenetTilt.getUpdateTime())) valid = true;

            // 声发射
            SlopeGeoacousticData geo = new SlopeGeoacousticData();
            geo.setDeviceSn(info.getDeviceSn());
            List<SlopeGeoacousticData> geoList = slopeGeoacousticDataService.selectSlopeGeoacousticDataList(geo);
            Date geoTime = geoList.isEmpty() ? null : geoList.stream()
                    .map(SlopeGeoacousticData::getUpdateTime)
                    .max(Date::compareTo)
                    .orElse(null);
            if (checkValid(geoTime)) valid = true;

            // 土壤湿度
            SlopeSoilData soilMoisture = slopeSoilDataService.getLatestSoilMoisture(info.getDeviceSn());
            if (checkValid(soilMoisture == null ? null : soilMoisture.getUpdateTime())) valid = true;

            // 土壤温度
            SlopeSoilData soilTemp = slopeSoilDataService.getLatestSoilTemperature(info.getDeviceSn());
            if (checkValid(soilTemp == null ? null : soilTemp.getUpdateTime())) valid = true;

            // 降雨量
            SlopeWeatherData rainfall = slopeWeatherDataService.getLatestRainfall(info.getDeviceSn());
            if (checkValid(rainfall == null ? null : rainfall.getUpdateTime())) valid = true;

            // 气温
            SlopeWeatherData weatherTemp = slopeWeatherDataService.getLatestTemperature(info.getDeviceSn());
            if (checkValid(weatherTemp == null ? null : weatherTemp.getUpdateTime())) valid = true;

            // 根据 valid 更新状态
            if (valid) {
                info.setCommStatus("在线");
                info.setDataStatus("正常");
            } else {
                info.setCommStatus("离线");
                info.setDataStatus("异常");
            }

            slopeDeviceInfoService.updateSlopeDeviceInfo(info);
        }
    }

    /**
     * 校验数据时间是否有效（非空且在2小时以内）
     */
    private boolean checkValid(Date dataTime) {
        if (dataTime == null) {
            return false;
        }
        long diff = System.currentTimeMillis() - dataTime.getTime();
        return diff <= 3 * 60 * 60 * 1000; // 2小时
    }

}
